/**************************************************************************************** 
 Copyright © 2003-2012 ZTEsoft Corporation. All rights reserved. Reproduction or       <br>
 transmission in whole or in part, in any form or by any means, electronic, mechanical <br>
 or otherwise, is prohibited without the prior written consent of the copyright owner. <br>
 ****************************************************************************************/
package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.api.scene.query.IQuerySceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.service.cache.CuccCustInfoDetailCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.entity.StaticAttrDO;
import com.ztesoft.bss.common.util.SpringUtil;

/** 
 * <Description> <br> 
 *  
 * @author tengg<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2021年3月16日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr <br>
 */
@Service
public class CustomerNatureHander extends AbstractAttrHandler {

    @Resource
    private IQuerySceneInstService querySceneInstService;
    
    @Autowired
    private OperateInstAttrService operateInstAttrService;
    
    /**
     * Description: <br> 
     *  
     * @author tengg<br>
     * @taskId <br>
     * @param commonAttr <br>
     */ 
    @Override
    public void init(CommonAttrVO commonAttr) {
        List<StaticAttrDO> attrValues = commonAttr.getAttrValues();
        if (KiteListUtils.isEmpty(attrValues)) {
            return;
        }
        List<StaticAttrDO> staticAttrs = Lists.newArrayList();
        // 根据客户证件，过滤客户性质下拉值
        CuccContextCustDTO custDTO1 = (CuccContextCustDTO) KiteWebContext.getContext().getCust();
        String certTypeCode = custDTO1.getCertiTypeCode();
        if (KiteStringUtils.isEmpty(certTypeCode)) {
            CuccCustInfoDetailDTO cuccCustInfoDTO = CuccCustInfoDetailCache.get(custDTO1.getCustId());
//            CuccCustInfoDetailDTO cuccCustInfoDTO = custReceptionService.getCustomerInfoNew(custDTO1.getCustId());
            if(Objects.nonNull(cuccCustInfoDTO)) {
                certTypeCode = cuccCustInfoDTO.getCertiTypeCode();
            }
        }
        
        if (KiteStringUtils.isNotEmpty(certTypeCode) && KiteStringUtils.isNotEmpty(IDTypeMap.get(certTypeCode))) {
            String idType = IDTypeMap.get(certTypeCode);
            List<String> strsToList1= Arrays.asList(idType.split(","));
            for (String str : strsToList1) {
                StaticAttrDO staticAttr = attrValues.stream().filter(attrValue -> KiteStringUtils.isEqual(str, attrValue.getAttrValue())).findFirst().orElse(null);
                if (Objects.nonNull(staticAttr)) {
                    staticAttrs.add(staticAttr);
                }
            }
        }
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);

        if (KiteListUtils.isNotEmpty(staticAttrs)) {
            commonAttr.setAttrValues(staticAttrs);
            KiteAttr kiteAttr = SpringUtil.getBean(IQuerySceneCommonService.class).getCommonAttr(sceneInstId,commonAttr.getFieldName()).getResultObject();
            if (Objects.nonNull(kiteAttr)) {
                List<KiteAttrValue> KiteAttrValues = Lists.newArrayList();
                String idType = IDTypeMap.get(certTypeCode);
                List<String> strsToList1= Arrays.asList(idType.split(","));
                for (String str : strsToList1) {
                    KiteAttrValue staticAttr = kiteAttr.getAttrValues().stream().filter(attrValue -> KiteStringUtils.isEqual(str, attrValue.getAttrValue())).findFirst().orElse(null);
                    if (Objects.nonNull(staticAttr)) {
                        KiteAttrValues.add(staticAttr);
                    }
                }
                kiteAttr.setAttrValues(KiteAttrValues);
                SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttr(sceneInstId, kiteAttr);
                
            }
//            setCommonAttr(commonAttr);
        }
        //订购之后的场景回填客户性质信息  使用模板配置订购时 需要做下拉值的匹配和映射
        List<KiteInst> prodInstList = querySceneInstService.listInsts(sceneInstId, Collections.singletonList(InstType.PROD_INST));
        prodInstList.forEach(prodInst ->{
            //申请单位性质
            KiteAttr kiteAttr = SpringUtil.getBean(IQuerySceneCommonService.class).getCommonAttr(sceneInstId,commonAttr.getFieldName()).getResultObject();
            KiteAttr prodAttr = querySceneInstService.getProdInstAttr(custDTO1.getCustId(), prodInst.getInstId(), "200001799");
            if (Objects.nonNull(prodAttr) && KiteStringUtils.isNotEmpty(prodAttr.getValue())) {
                List<KiteAttrValue> valueList = kiteAttr.getAttrValues();
                if(valueList.size()>0) {
                    int i = 0;
                    for (KiteAttrValue value : valueList) {
                        if(KiteStringUtils.equals(prodAttr.getValue(),value.getAttrValue())){
                            i++;
                            break;
                        }
                    }
                    if(i > 0){
                        commonAttr.setValue(prodAttr.getValue());
                        commonAttr.setValueDesc(prodAttr.getValueDesc());
                    } else {
                        //没有匹配到下拉数据就清空，重新选择新的数据信息
                        commonAttr.setValue("");
                        commonAttr.setValueDesc("");
                    }
                }
            }
        });

        // 业务变更场景是  客户性质不可修改
        IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);
        if("2826".equals(sceneInst.getServiceOfferId()) && KiteStringUtils.isNotEmpty(commonAttr.getValue())){
            commonAttr.setIsEdit("F");
            KiteAttr custNatureAttr = querySceneInstService.getCommonAttr(sceneInstId, "200001799");
            if (Objects.nonNull(custNatureAttr)) {
                custNatureAttr.setIsEdit("F");
                operateSceneInstService.setCommonAttr(sceneInstId, custNatureAttr);
            }
        }
    }
    
    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        // super.apply(sceneInstId, fieldName, value, valueDesc);
        if (KiteStringUtils.isNotEmpty(value)) {
            CuccContextCustDTO custDTO1 = (CuccContextCustDTO) KiteWebContext.getContext().getCust();
            //查询这个offer下有效的接入产品
            List<KiteInst> prodInstList = querySceneInstService.listInsts(sceneInstId, Collections.singletonList(InstType.PROD_INST));
            prodInstList.forEach(prodInst ->{
                //赋值给单位性质
                KiteAttr prodAttr = querySceneInstService.getProdInstAttr(custDTO1.getCustId(), prodInst.getInstId(), "200001799");
                if (Objects.nonNull(prodAttr) && !KiteStringUtils.isEqual(prodAttr.getValue(), value)) {
                    operateInstAttrService.setAttrValue(prodInst, prodAttr.getFieldName(), value, sceneInstId, null);
                }
            });
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        return ErrorConsts.SUCCESS.getResult(true);
    }
    
    private static Map<String, String> IDTypeMap = new HashMap<>();
    
    static {
        IDTypeMap.put("0", "1_0000423");
        IDTypeMap.put("1", "1_0000423");
        IDTypeMap.put("2", "1_0000423");
        IDTypeMap.put("3", "1_0000423");
        IDTypeMap.put("5", "1_0000423");
        IDTypeMap.put("6", "1_0000423");
        IDTypeMap.put("7", "1_0000423");
        IDTypeMap.put("9", "1_0000423");
        IDTypeMap.put("8", "1_0000423");
        IDTypeMap.put("L", "100002198");
        IDTypeMap.put("M", "100002199");
        IDTypeMap.put("R", "1_0000421");
        IDTypeMap.put("S", "1_0000420,100002198,1_0000421,100002199,110007013,1_0000422,110007012");
        IDTypeMap.put("G", "1_0000423");
        IDTypeMap.put("4", "1_0000422");
    }
}
